<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="活动名称" prop="activityName">
        <el-input
          v-model="queryParams.activityName"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动主题" prop="activityTheme">
        <el-select
          v-model="queryParams.activityTheme"
          placeholder="请选择活动主题"
          clearable
        >
          <el-option
            v-for="dict in activity_theme"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 卡片布局 -->
    <el-row :gutter="20">
      <el-col
        v-for="(item, index) in activityList"
        :key="index"
        :xs="24"
        :sm="12"
        :md="8"
        :lg="4"
        class="mb-20"
      >
        <el-card
          shadow="hover"
          class="activity-card"
          @click="handleUpdate(item)"
        >
          <div class="card-image" @click.stop="showDetail(item)">
            <img
              :src="item.activityCover"
              style="width: 100%; height: 150px; object-fit: cover"
            />
          </div>
          <div class="card-content">
            <h4 class="title">{{ item.activityName }}</h4>
            <p class="time">
              发布时间：{{ parseTime(item.createTime, "{y}-{m}-{d}") }}
            </p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      :pageSizes="[12, 24]"
      @pagination="getList"
    />

    <!-- 详情弹窗 -->
    <el-dialog
      :title="currentActivity.activityName"
      v-model="detailVisible"
      width="600px"
      append-to-body
    >
      <div class="detail-container">
        <div class="detail-image">
          <img
            :src="currentActivity.activityCover"
            style="width: 100%; max-height: 300px; object-fit: contain"
          />
        </div>
        <div class="detail-content">
          <div class="detail-item">
            <span class="detail-label">活动主题：</span>
            <dict-tag
              :options="activity_theme"
              :value="currentActivity.activityTheme"
            />
          </div>
          <div class="detail-item">
            <span class="detail-label">发布时间：</span>
            <span>{{
              parseTime(currentActivity.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">结束时间：</span>
            <span>{{
              parseTime(currentActivity.endTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">参与人数：</span>
            <span
              >{{ currentActivity.participantsNum }}/{{
                currentActivity.maxParticipantsNum
              }}
              人</span
            >
          </div>
          <div class="detail-body">
            <div class="detail-label">活动内容：</div>
            <div class="detail-text">{{ currentActivity.activityBody }}</div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            @click="handleJoin(currentActivity)" 
            v-if="!activityStatusMap[currentActivity.activityId]"
          >参加活动</el-button>
          <el-button 
            type="primary" 
            @click="handleQuit(currentActivity)" 
            v-else
            :disabled="true"
          >您已参与该活动</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Challenge">
import { listActivity, getActivity, delActivity, addActivity, updateActivity, takePartActivity, listActivityUser } from "@/api/manage/activity"
import useUserStore from '@/store/modules/user'
import { ref } from "vue"

const userStore = useUserStore()

const { proxy } = getCurrentInstance()
const { activity_theme } = proxy.useDict('activity_theme')

const activityList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 12,
    activityName: null,
    activityTheme: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询活动列表 */
function getList () {
  loading.value = true
  listActivity(queryParams.value).then(response => {
    activityList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel () {
  open.value = false
  reset()
}

// 表单重置
function reset () {
  form.value = {
    activityId: null,
    activityName: null,
    activityBody: null,
    activityTheme: null,
    activityCover: null,
    participantsNum: null,
    maxParticipantsNum: null,
    createTime: null,
    endTime: null
  }
  proxy.resetForm("activityRef")
}

/** 搜索按钮操作 */
function handleQuery () {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery () {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange (selection) {
  ids.value = selection.map(item => item.activityId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd () {
  reset()
  open.value = true
  title.value = "添加活动"
}

/** 修改按钮操作 */
function handleUpdate (row) {
  reset()
  const _activityId = row.activityId || ids.value
  getActivity(_activityId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改活动"
  })
}

/** 提交按钮 */
function submitForm () {
  proxy.$refs["activityRef"].validate(valid => {
    if (valid) {
      if (form.value.activityId != null) {
        updateActivity(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addActivity(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete (row) {
  const _activityIds = row.activityId || ids.value
  const delName = _activityIds.length >= 1 ? '选中的活动' : row.activityName
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function () {
    return delActivity(_activityIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport () {
  proxy.download('manage/activity/export', {
    ...queryParams.value
  }, `activity_${new Date().getTime()}.xlsx`)
}

const detailVisible = ref(false)
const currentActivity = ref({})

// 替换原来的 activityStatus 定义
const activityStatusMap = ref({}) // 使用对象存储每个活动的参与状态

function showDetail(item) {
  currentActivity.value = item
  detailVisible.value = true
  userStore.getInfo().then(userInfo => {
    let data = {
      activityId: item.activityId
    }
    listActivityUser(data).then(response => {
      // 更新当前活动的参与状态
      activityStatusMap.value[item.activityId] = response.data !== null && response.data.length > 0
    })
  })
}

function handleJoin(activity) {
  let data = {
    activityId: activity.activityId
  }
  takePartActivity(data).then(response => {
    if (response.code == 200) {
      proxy.$modal.msgSuccess("参加活动成功")
      // 更新当前活动的参与状态
      activityStatusMap.value[activity.activityId] = true
      getList() // 刷新列表数据
    }
    detailVisible.value = false
  })
}
getList();
</script>

<style lang="scss" scoped>
.activity-card {
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 20px;
  padding: 0; /* 移除卡片内边距 */
}

:deep(.el-card__body) {
  padding: 0 !important;
  height: 100%;
}

.activity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-image {
  height: 150px;
  overflow: hidden;
  margin: 0; /* 移除图片外边距 */
}

.card-content {
  padding: 15px;
}

.card-content .title {
  margin: 0 0 8px 0;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-content .time {
  margin: 0;
  font-size: 12px;
  color: #999;
}

.detail-container {
  padding: 10px 60px 10px 60px;
}

:deep(el-dialog__body) {
  padding: 0 !important;
  height: 100%;
}

.detail-image {
  margin-bottom: 20px;
  text-align: center;
}

.detail-content {
  padding: 0 10px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-body {
  margin-top: 20px;
  width: 100%;
}

.detail-body .detail-label {
  color: #606266;
  margin-bottom: 8px;
}

.detail-text {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
  white-space: pre-wrap;
}
</style>
